<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/11
 * Time: 9:32
 */
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\admin\model\Banner as BannerModel;
class Push extends Common
{
    /*
    * 系统消息
    */
    public function system()
    {
        //获取数据库的信息用于展示
        if (Request::instance()->isAjax()) {
            $pagedata = Request::instance()->get();
            $pagesize = $pagedata['limit'];
            $page = (int)$pagedata['page'];
            if ($page == 1) {
                $startrow = 0;
            } else {
                $startrow = ($page - 1) * $pagesize;
            }
            $count = Db::name('user')->count();
            $data = Db::name('user')
                ->field('uid,phone,nickname')
                ->limit($startrow, $pagesize)
                ->order('uid', 'desc')
                ->select();
            return json(array('code' => 0, 'msg' => '请求成功', 'count' => $count, 'data' => $data));

        } else {
            //查询所用用户
            $user = Db::name('user')->field('uid,nickname')->select();
            $this->assign('user',$user);
            return $this->fetch();
        }
    }
    /*
     * 单个的发送系统消息
     */
    public function send()
    {
        if (Request::instance()->isAjax()) {
            $post = Request::instance()->post();
            $data = $post['data'];
            //给这个用户发送系统消息
            $datas = [
                'receive_user_id'=>$data['uid'],
                'msg_content'=>$data['msg_content'],
                'msg_title' =>$data['msg_title'],
                'msg_type'=>1,
                'create_time'=>date('Y-m-d H:i:s'),
                'is_read'=>0
            ];
            $res = Db::name('message')->insert($datas);
            if($res){
                return 1;
            }else{
                return 2;
            }
        }
    }
    /*
     * 多选发送
     */
    public function more_send()
    {
        if (Request::instance()->isAjax()) {
            $post = Request::instance()->post();
            //转换成数组
            $uid = explode(',',$post['id']);
            $data =[];
            foreach($uid as $key =>$v){
                $data[] = [
                    'receive_user_id'=>$v,
                    'msg_content'=>$post['content'],
                    'msg_title' =>$post['title'],
                    'create_time'=>date('Y-m-d H:i:s'),
                    'msg_type'=>1,
                    'is_read'=>0
                ];
            }
            $res = Db::name('message')->insertAll($data);
            if($res){
                return 1;
            }else{
                return 2;
            }

        }
    }

}